import { effects } from 'dva-core/saga';
import Taro from '@tarojs/taro';
import Payment from './payment';
import Network, { setupTrace } from './network';
import { loginWexin } from '../wexin';
import sensor from '../../../utils/sensorsdata';

export const loading = {
    show: wx.showLoading,
    hide: wx.hideLoading
};

const header = () => {};

export { Payment, Network, header, setupTrace };

export const getSystemInfoSync = wx.getSystemInfoSync;
export const getSystemInfo = wx.getSystemInfo;

export const stopPullDownRefresh = wx.stopPullDownRefresh;
export const setNavigationBarTitle = wx.setNavigationBarTitle;

export const createSelectorQuery = wx.createSelectorQuery;
export const uploadFile = Taro.uploadFile;

export { action, delay} from '../action';
export class Authientication{
    constructor(options = {
        loginPage: '/pages/login/index',
        authPage: '/sso/passport/login_miniapp',
        withProfile: 1
    }){
        this.options = options;
    }

    *auth () {
        // 先用页面静默登录，登录失败了之后再跳转到登录页
        const code = yield loginWexin();
        const data = yield effects.put.resolve({
            type: '$request/post',
            payload: {
                url: '/api/login',
                data: {
                    jsCode: code,
                    appId: this.options.appId
                }
            }
        });
        // 登录成功
        if (data) {
            const {token,openid} = data;
            sensor.login(openid);
            console.log('token:',token);
            yield effects.put.resolve({
                type: '$storage/set',
                payload: {
                    key : 'token',
                    value : token
                }
            });
            wx.setStorageSync('open_id', openid);

            const pages = Taro.getCurrentPages();
            const perpage = pages[pages.length - 1];
            perpage.onReady();  
            perpage.onLoad();  
            perpage.onShow();  
        }else{ }
    }
    *silentAuth(){

    }
}
